package OS

import (
	"errors"
	"gitee.com/fierce_wolf/go-fox-edge-common/commUtil/Charts"
	"os/exec"
	"strings"
)

type windowsCmd struct {
}

func (e *windowsCmd) getChartType() string {
	if !Type.IsWindows() {
		return ""
	}

	cmd := exec.Command("chcp")
	out, err := execCmd(cmd)
	if err != nil {
		return ""
	}

	str := out.String()
	items := strings.Split(str, ": ")
	if len(items) < 2 {
		return ""
	}

	code := items[len(items)-1]
	if strings.HasSuffix(code, "\r\n") {
		code = code[0 : len(code)-2]
	}

	// GB2312
	if code == "936" {
		return "GB2312"
	}

	return ""
}

func (e *windowsCmd) ExecCmd(cmd *exec.Cmd) (string, error) {
	if !Type.IsWindows() {
		return "", errors.New("不是windows环境")
	}

	out, err := execCmd(cmd)
	if err != nil {
		return "", err
	}

	if "GB2312" == chartSet {
		return Charts.GbkToUtf8Str(out.Bytes())
	} else {
		return out.String(), nil
	}
}

func (e *windowsCmd) Exec(cmd *exec.Cmd) ([]string, error) {
	out, err := e.ExecCmd(cmd)
	if err != nil {
		return nil, err
	}

	lines := strings.Split(out, "\r\n")

	return lines, nil
}
